package com.liang.codegenerate.controller;

import com.liang.codegenerate.common.BaseResponse;
import com.liang.codegenerate.common.ErrorCode;
import com.liang.codegenerate.common.ResultUtils;
import com.liang.codegenerate.exception.BusinessException;
import com.liang.codegenerate.model.dto.fields.FieldsAddDto;
import com.liang.codegenerate.model.dto.fields.FieldsUpdateDto;
import com.liang.codegenerate.model.entity.Fields;
import com.liang.codegenerate.service.FieldsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/fields")
public class FieldsController {

    @Resource
    private FieldsService fieldsService;

    @PostMapping("/add")
    public BaseResponse<Boolean> addField(@RequestBody FieldsAddDto fieldsAddDto){
        if (fieldsAddDto == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = fieldsService.addField(fieldsAddDto);
        return ResultUtils.success(b);
    }

    @GetMapping("/list")
    public BaseResponse<List<Fields>> listField(@RequestParam Long tableId){
        if (tableId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<Fields> fields = fieldsService.listField(tableId);
        return ResultUtils.success(fields);
    }

    @GetMapping("/list/id")
    public BaseResponse<Fields> listFieldById(@RequestParam Long id){
        if (id == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Fields fields = fieldsService.listFieldById(id);
        return ResultUtils.success(fields);
    }

    @PutMapping("/update")
    public BaseResponse<Boolean> updateField(@RequestBody FieldsUpdateDto fieldsUpdateDto){
        if (fieldsUpdateDto == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = fieldsService.updateField(fieldsUpdateDto);
        return ResultUtils.success(b);
    }

    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteField(@RequestParam Long id){
        if (id == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = fieldsService.deleteField(id);
        return ResultUtils.success(b);
    }
}
